﻿using ESRI.ArcGIS.AnalysisTools;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geoprocessor;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.International.Converters.PinYinConverter;

namespace AEFunction.UI
{
    public partial class BatchClipByFeatureToRaster : Form
    {
        private ILayer[] featureLayers;
        private ToolStripProgressBar pb1;
        private AxMapControl mc;
        public BatchClipByFeatureToRaster(ToolStripProgressBar p, AxMapControl m, ILayer[] layers)
        {
            InitializeComponent();
            pb1 = p;
            mc = m;
            featureLayers = layers;
            for (int i = 0; i < layers.Length; i++)
            {
                ThisItem ti = new ThisItem(layers[i]);
                comboBox1.Items.Add(ti);
                comboBox2.Items.Add(ti);
                comboBox3.Items.Add(ti);
            }
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox3.SelectedIndex = 0;
        }

        private void button4_Click(object sender, EventArgs e)
        {


            IFeatureLayer clipFeature = (IFeatureLayer)((ThisItem)comboBox2.SelectedItem).layer;
            IFeatureLayer inputFeature = (IFeatureLayer)((ThisItem)comboBox1.SelectedItem).layer;
            IFeatureLayer landLayer = (IFeatureLayer)((ThisItem)comboBox3.SelectedItem).layer;
            string exportPath = OutputTxt.Text;
            string tmpPath = exportPath + "\\tmp";
            if (!Directory.Exists(tmpPath))
            {
                // Create the directory it does not exist.
                Directory.CreateDirectory(tmpPath);
            }
            else
            {
                // Delete the target to ensure it is not there.
                Directory.Delete(tmpPath, true);
                Directory.CreateDirectory(tmpPath);
            }
            
            IFeatureSelection pFeatureSelection;
            pFeatureSelection = clipFeature as IFeatureSelection;
            IFeatureClass clipFeatureClass = clipFeature.FeatureClass;

            Geoprocessor GP = new Geoprocessor();
            Clip clip = new Clip();
            GP.OverwriteOutput = true;
            int FeatureCount = clipFeatureClass.FeatureCount(null);
            pb1.Maximum = FeatureCount;
            IPnt p = new PntClass();
            p.X = 30;
            p.Y = 30;
            IField f = inputFeature.FeatureClass.Fields.get_Field(35);//pFeature.Fields.get_Field(36);
            for (int i = 0; i < FeatureCount; i++)
            {
                pb1.Value++;
                pFeatureSelection.Clear();
                IFeature pFeature = clipFeatureClass.GetFeature(i);

                ISpatialFilter spatialFilter = new SpatialFilterClass();
                spatialFilter.Geometry = pFeature.Shape;
                spatialFilter.SpatialRel = ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects;
                IFeatureCursor featureCursor = landLayer.FeatureClass.Search(spatialFilter, false);
                IFeature tmpF = featureCursor.NextFeature();
                if (tmpF == null)
                    continue;

                pFeatureSelection.SelectionSet.Add(pFeature.OID);
                string streetName = (string)pFeature.get_Value(4);
                string streetPY = GetPinyin(streetName);
                clip.clip_features = pFeatureSelection as IFeatureLayer;

                clip.in_features = inputFeature;
                clip.out_feature_class = tmpPath + "\\" + streetPY;
                clip.cluster_tolerance = 0;
                GP.Execute(clip, null);
                //mc.AddShapeFile(tmpPath,streetName);
                
                //ESRI.ArcGIS.ConversionTools.PolygonToRaster pr = new ESRI.ArcGIS.ConversionTools.PolygonToRaster();
                //pr.in_features = ((IFeatureLayer)mc.get_Layer(0)).FeatureClass;
                //pr.value_field = "FLBM";
                //pr.out_rasterdataset = exportPath + "\\StreetRaster.mdb\\"+streetName;
                //pr.cellsize = 30;

               
                //GP.Execute(pr, null);
            }
            pb1.Value = 0;
            MessageBox.Show("裁剪完成。");
            this.DialogResult = DialogResult.OK;
        }

        // <summary>
        /// 汉字转化为拼音
        /// </summary>
        /// <param name="str">汉字</param>
        /// <returns>全拼</returns>
        public static string GetPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, t.Length - 1).ToLower();
                    
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        /// <summary>
        /// 汉字转化为拼音首字母
        /// </summary>
        /// <param name="str">汉字</param>
        /// <returns>首字母</returns>
        public static string GetFirstPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                OutputTxt.Text = fbd.SelectedPath;
            }
        }

        private IFeatureLayer GetFeatureLayerFromShapeFile(string path)
        {
            int Position = path.LastIndexOf("\\");
            string FilePath = path.Substring(0, Position);
            string ShpName = path.Substring(Position + 1);
            IWorkspaceFactory factory = new ShapefileWorkspaceFactoryClass();
            IWorkspace workspace = factory.OpenFromFile(FilePath, 0);
            IFeatureWorkspace featureworkspace = workspace as IFeatureWorkspace;
            IFeatureClass featureclass = featureworkspace.OpenFeatureClass(ShpName);
            IFeatureLayer layer = new FeatureLayerClass();
            layer.FeatureClass = featureclass;
            layer.Name = ShpName.Split('.')[0];
            return layer;
        }

        public static bool ToRaster(IFeatureClass feaureClass, string fieldName, String rasterWorkspace, String rasterName, int cellSize)
        {

            string fullPath;

            IGeoProcessor pGP;

            IGeoProcessorResult pGPR;

            IVariantArray pParameterArray;

            try
            {

                fullPath = System.IO.Path.Combine(rasterWorkspace, rasterName);

                if (System.IO.File.Exists(fullPath))
                {

                    //删除已经存在的文件                    

                    System.IO.File.Delete(fullPath);

                }

                pGP = new GeoProcessorClass();

                pParameterArray = new VarArrayClass();

                pParameterArray.Add(feaureClass);

                pParameterArray.Add(fieldName);

                pParameterArray.Add(rasterWorkspace + @"\" + rasterName);

                pParameterArray.Add("MAXIMUM_AREA");

                pParameterArray.Add(null);

                pParameterArray.Add(cellSize);

                //Convertion Tools(PolygonToRaster_conversion)                

                pGPR = pGP.Execute("PolygonToRaster_conversion", pParameterArray, null);

                return true;

            }

            catch (Exception ex)
            {

                throw ex;

            }

        }

        private void BatchClipByFeatureToRaster_Load(object sender, EventArgs e)
        {

        }
    }

    class ThisItem
    {
        public ILayer layer;
        public override string ToString()
        {
            return layer.Name;
        }
        public ThisItem(ILayer l)
        {
            layer = l;
        }
    }
}
